<script lang="ts" setup>
import { getSafeInfo } from '@/utils/system'
import { useToast } from 'wot-design-uni'

defineOptions({ name: 'JediTagInput' })

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue'])

const { warning: showWarning } = useToast()

const safeInfo = getSafeInfo()
const realSafeBottom = computed(() => {
  return `${safeInfo.bottom}px`
})
const show = ref(false)
const tagValue = ref('')
const skillArr = ref([])
watch(
  () => props.modelValue,
  (newValue) => {
    skillArr.value = newValue.split(',')
  },
  { immediate: true },
)
const handleOpen = () => {
  show.value = true
}
const handleClose = () => {
  show.value = false
}
const handleCancel = () => {
  handleClose()
  skillArr.value = props.modelValue.split(',')
  tagValue.value = ''
}
const handleConfirm = () => {
  const val = skillArr.value.join(',')
  emit('update:modelValue', val)
  handleClose()
}
const handleChange = (val) => {}
const handleDelete = (index) => {
  skillArr.value.splice(index, 1)
}
const addTag = (index) => {
  if (tagValue.value) {
    skillArr.value.push(tagValue.value)
    tagValue.value = ''
  }
  else {
    showWarning({ msg: '请输入标签' })
  }
}
</script>

<template>
  <wd-input
    v-bind="$attrs"
    :model-value="modelValue"
    suffix-icon="arrow-right"
    readonly
    @change="handleChange"
    @click="handleOpen"
  />
  <wd-popup
    v-model="show"
    position="bottom"
    custom-style=""
    @close="handleClose"
  >
    <view class="bottomLine h-10 flex items-center px-2 px-3">
      <text class="text-desc" @click="handleCancel">
        取消
      </text>
      <view class="w-4 flex-1 text-center">
        编辑标签
      </view>
      <text class="primaryColor" @click="handleConfirm">
        确认
      </text>
    </view>
    <view class="p-3" :style="{ paddingBottom: realSafeBottom }">
      <!-- <wd-tag closable round type="primary" @close="handleDelete">
        标签
      </wd-tag> -->
      <wd-notice-bar
        text="最多编辑6个标签"
        prefix="warn-bold"
        :scrollable="false"
      />
      <view class="mb-1 mt-3 flex flex-wrap gap-2">
        <sar-tag
          v-for="(tag, tIndex) in skillArr"
          :key="tag"
          theme="primary"
          size="large"
          closable
          @close="handleDelete(tIndex)"
        >
          {{ tag }}
        </sar-tag>
      </view>
      <wd-gap bg-color="#FFFFFF" />
      <wd-input v-model="tagValue" placeholder="请输入标签" :maxlength="10">
        <template #suffix>
          <wd-button size="small" icon="add" @click="addTag">
            添加
          </wd-button>
        </template>
      </wd-input>
      <wd-gap bg-color="#FFFFFF" height="20rpx" />
    </view>
  </wd-popup>
</template>

<style lang="scss" scoped>
</style>
